package cn.com.lyj6851.auth.authentication;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.com.lyj6851.common.properties.LoginResponseType;
import cn.com.lyj6851.common.properties.RootSecurityProperties;
import cn.com.lyj6851.common.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 认证失败处理器
 * @author Administrator
 *
 */
@Slf4j
@Component
public class YongAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler{
	
	@Autowired
    private RootSecurityProperties securityProperties;
	@Autowired
    private ObjectMapper objectMapper;
	
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		log.info("登录失败");
		/**
		 * 处理逻辑:
		 * 如果配置文件配置以json返回则,返回json
		 * 否走框架默认逻辑
		 */
		if(LoginResponseType.JSON.equals(securityProperties.getBrowser().getLoginType())) {
			response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
		    response.setContentType("application/json;charset=UTF-8");
		    response.getWriter().write(objectMapper.writeValueAsString(ResultUtil.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),exception.getMessage())));
		}else {
			 super.onAuthenticationFailure(request, response, exception);
		}
	}
}
